package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;
    @Override
    public Map search(Map<String, String> searchMap) {
        //构建要返回的map
        Map<String,Object> resultMap = new HashMap<>();
        //构建请求
        if (searchMap!=null){
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //关键字查询
            if (StringUtils.isNotEmpty(searchMap.get("keywords"))){
                boolQueryBuilder.must(QueryBuilders.matchQuery("name",searchMap.get("keywords")).operator(Operator.AND));
            }
            //品牌查询
            if (StringUtils.isNotEmpty(searchMap.get("brand"))){
                boolQueryBuilder.must(QueryBuilders.termQuery("brandName",searchMap.get("brand")));
            }
            //规格过滤
            //http://localhost:9009/search?keywords=手机&spec_颜色=红色&spec_网络制式=电信3G&spec_版本=8G%2B256G
            //遍历searchMap
            for (String key : searchMap.keySet()) {
                //如果key的开始里有spec_
                if (key.startsWith("spec_")){
                    String value = searchMap.get(key).replace("%2B", "+");
                    boolQueryBuilder.filter(QueryBuilders.termQuery("specMap."+key.substring(5)+".keyword",value));
                }
            }
            //价格区间查询
            if (StringUtils.isNotEmpty(searchMap.get("price"))){
                String[] prices = searchMap.get("price").split("-");
//                if (prices.length==2){
//                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(prices[0]).lte(prices[1]));
//                }else{
//                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
//                }
                RangeQueryBuilder price = QueryBuilders.rangeQuery("price").gte(prices[0]);
                if (prices.length==2){
                    price.lte(prices[1]);
                }
                boolQueryBuilder.filter(price);
            }

            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            //品牌聚合
            String skuBrand = "skuBrand";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));
            //规格聚合
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));
            //分页展示
            //起始页
            String pageNum = searchMap.get("pageNum");
            if (StringUtils.isEmpty(pageNum)){
                pageNum="1";
            }
            //每页显示几条
            String pageSize = searchMap.get("pageSize");
            if (StringUtils.isEmpty(pageSize)){
                pageSize="30";
            }
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1,Integer.parseInt(pageSize)));
            //排序
            if (StringUtils.isNotEmpty(searchMap.get("sortField"))&&StringUtils.isNotEmpty(searchMap.get("sortRule"))){
                if ("ASC".equals(searchMap.get("sortRule"))){
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.ASC));
                }else {
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.DESC));
                }
            }
            // 指定高亮字段：name字段。关键词前后加标签。
            //1指定高亮字段：name字段
            HighlightBuilder.Field field = new HighlightBuilder.Field("name");
            //2 关键词前后加标签
            field.preTags("<span style='color:red'>");
            field.postTags("</span>");
            //3高亮字段 告诉搜索条件
            nativeSearchQueryBuilder.withHighlightFields(field);

            AggregatedPage<SkuInfo> skuInfos = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    //获取查询结果
                    SearchHits hits = searchResponse.getHits();
                    //封装到
                    List<T> skuInfoList = new ArrayList<>();
                    if (hits!=null){
                        for (SearchHit hit : hits) {
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                            // 将高亮字段提取，替换高亮字段:name。
                            //1获取高亮字段 name
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if (highlightFields!=null&&highlightFields.size()>0){
                                //2设置skuInfo name属性为高亮属性
                                String name = highlightFields.get("name").getFragments().toString();
                                skuInfo.setName(name);
                            }
                            skuInfoList.add((T) skuInfo);
                        }
                    }
                    //构建返回对象
                    return new AggregatedPageImpl<>(skuInfoList, pageable, hits.getTotalHits(), searchResponse.getAggregations());

                }
            });
            //封装最终返回结果
            //返回总记录数
            resultMap.put("total",skuInfos.getTotalElements());
            //总页数
            resultMap.put("totalPages",skuInfos.getTotalPages());
            //数据集合
            resultMap.put("rows",skuInfos.getContent());
            //品牌集合
            StringTerms brandTerms = (StringTerms) skuInfos.getAggregation(skuBrand);
//            List<String> brandList = new ArrayList<>();
//            List<StringTerms.Bucket> buckets = brandTerms.getBuckets();
//            for (StringTerms.Bucket bucket : buckets) {
//                brandList.add(bucket.getKeyAsString());
//            }
            //表达式方法
            List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList",brandList);
            //规格集合
            StringTerms specTerms = (StringTerms) skuInfos.getAggregation(skuSpec);
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList",this.formartSpec(specList));

        }
        return resultMap;
    }
    //规格信息数据转换
    public Map<String, Set<String>> formartSpec(List<String> specList){
        //1定义返回map
        Map<String,Set<String>> resultMap= new HashMap<>();
        //2遍历specList
        if (specList!=null &&specList.size()>0){
            for (String specJsonString : specList) {
                // 将json转为map
                Map<String,String> specMap = JSON.parseObject(specJsonString, Map.class);
                //遍历每个商品的规格名字
                for (String specKey : specMap.keySet()) {
                    Set<String> specSet = resultMap.get(specKey);
                    if (specSet==null){
                        specSet = new HashSet<>();
                    }
                    //将此条数据中的规格放入set
                    specSet.add(specMap.get(specKey));
                    //将set放入返回map
                    resultMap.put(specKey, specSet);
                }
            }
        }
        return resultMap;
    }
}
